package com.example.service;

import com.example.entity.User;
import com.example.enums.UserStatusEnum;
import com.example.enums.UserTypeEnum;
import com.example.exception.CustomerException;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class LoginService {

    @Resource
    UserMapper userMapper;

    public User login(User user) {
        //验证账号是否存在
        User dbuser = userMapper.selectByUsername(user.getUsername());
        if (dbuser == null) {
            throw new CustomerException("账号不存在");
        }
        //验证密码是否正确
        if (!dbuser.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))) {
            throw new CustomerException("账号或密码错误");
        }
        if (dbuser.getStatus().equals(UserStatusEnum.DISABLE.getStatusId())){
            throw new CustomerException("此账号已被禁用");
        }
        String token;
        Integer roleId = dbuser.getUserType();
        UserTypeEnum usertype = UserTypeEnum.getUserType(roleId);
        if (usertype == null) {
            throw new CustomerException("无此用户类型");
        }else {
            token = TokenUtils.createToken(roleId + "-" + usertype.getRoleName(), dbuser.getPassword());
            dbuser.setToken(token);
        }
        dbuser.setLastLogin(LocalDateTime.now());
        userMapper.updateById(dbuser);
        return dbuser;
    }
}
